<template>
  <div class="dialog">
    <el-dialog
      :title="'维修记录'+titleText"
      :visible.sync="showDialog"
      width="55%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-form
        ref="ruleForm"
        label-position="left"
        :model="formData"
        :rules="rules"
        class="el-form"
      >
        <el-form-item label="故障类型选择：" class="w50p" prop="hitchTypeCode">
          <el-select
            v-model="formData.hitchTypeCode"
            clearable
            filterable
            placeholder="故障类型选择"
            :disabled="!canInput"
          >
            <el-option
              v-for="item of hitchTypeArr"
              :key="item.hitchTypeCode"
              :label="item.hitchTypeName"
              :value="item.hitchTypeCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择设备类型：" class="w50p" prop="equipmentTypeCode">
          <el-cascader
            v-model="formData.equipmentTypeCode"
            :props="defaultProps"
            :options="equipmentTypeList"
            :show-all-levels="false"
            clearable
            :disabled="!canInput"
            placeholder="请选择所属设备类型"
            @change="changeEquipmentTypeCode"
          />
        </el-form-item>
        <el-form-item label="选择设备：" class="w50p" prop="equipmentCode">
          <el-select
            v-model="formData.equipmentCode"
            clearable
            filterable
            placeholder="选择设备"
            :disabled="!canInput"
          >
            <el-option
              v-for="item in equipmentArr"
              :key="item.equipmentCode"
              :label="item.equipmentName"
              :value="item.equipmentCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择关键字：" class="w50p" prop="repairWordBOList">
          <el-select
            v-model="formData.repairWordBOList"
            clearable
            filterable
            multiple
            :disabled="!canInput"
            placeholder="选择关键字"
            @change="changeKey"
          >
            <el-option
              v-for="item in keysArr"
              :key="item.keywordCode"
              :label="item.hitchKeywordName"
              :value="item.keywordCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="故障节点：" class="w50p" prop="discoverNodes">
          <el-select
            v-model="formData.discoverNodes"
            clearable
            filterable
            placeholder="故障节点选择"
            :disabled="!canInput"
          >
            <el-option
              v-for="item of discoverNodesArr"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="故障照片、视频：" class="w50p">
          <!-- <MultipleUpMany
            :can-input="false"
            @gave-files="gaveFiles"
          />-->
          <el-upload
            ref="upload"
            class="upload-file"
            action
            multiple
            :on-remove="
              params =>
                handleRemove(
                  params
                )
            "
            :https-request="
              params =>
                handleFile(
                  params
                )
            "
            :file-list="uploadFileList"
            accept=".png, .jpg, .jpeg, .pdf, .mp4"
            :disabled="!canInput"
          >
            <el-button type="text" class="add-many">
              <i class="el-icon-plus"></i>
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="上报人：" class="w50p" prop="proposer">
          <el-select
            v-model="formData.proposer"
            clearable
            filterable
            placeholder="上报人选择"
            :disabled="!canInput"
          >
            <el-option
              v-for="item of userList"
              :key="item.userId"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上报日期 ：" class="w50p" prop="applyDate">
          <el-date-picker
            v-model="formData.applyDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            clearable
            :disabled="!canInput"
          />
        </el-form-item>
        <el-form-item label="截止日期 ：" class="w50p" prop="expiryDate">
          <el-date-picker
            v-model="formData.expiryDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            clearable
            :disabled="!canInput"
          />
        </el-form-item>

        <el-form-item label="维修方式 ：" class="w50p" prop="repairNature">
          <el-select
            v-model="formData.repairNature"
            clearable
            filterable
            placeholder="维修方式选择"
            :disabled="true"
          >
            <el-option
              v-for="item of repairNatureArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备件消耗：" class="w50p">
          <div class="line-click" @click="canInput?addDeviceCodes():''">
            <i class="el-icon-plus"></i>
          </div>
          <div class="hang-content">
            <div
              v-for="(key,index) in formData.repairConsumeBOList"
              :key="index+'deviceCode'"
              class="hang-content-one"
            >
              <el-select
                v-model="key.deviceCode"
                clearable
                filterable
                placeholder="备件选择"
                :disabled="!canInput"
              >
                <el-option
                  v-for="(item,indexK) of sparePartArr"
                  :key="item.sparePartCode+'spare'+indexK"
                  :label="item.sparePartName"
                  :value="item.sparePartCode"
                />
              </el-select>
              <el-input
                v-model="key.num"
                clearable
                placeholder="请填写数量"
                :disabled="!canInput"
              />

              <div
                class="line-click"
                @click="canInput?delDeviceCodes(index):''"
              >
                <i class="el-icon-minus"></i>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="维修费用：" class="w50p" prop="cost">
          <el-input
            v-model="formData.cost"
            clearable
            placeholder="请输入维修费用"
            :disabled="!canInput"
          />
        </el-form-item>
        <el-form-item label="维修日期 ：" class="w50p" prop="repairDate">
          <el-date-picker
            v-model="formData.repairDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            clearable
            :disabled="!canInput"
          />
        </el-form-item>
        <el-form-item label="维修人：" class="w50p" prop="handUsername">
          <el-select
            v-model="formData.handUsername"
            clearable
            filterable
            placeholder="维修人选择"
            :disabled="!canInput"
          >
            <el-option
              v-for="item of userList"
              :key="item.userId"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维修结果：" class="w50p" prop="result">
          <el-select
            v-model="formData.result"
            clearable
            filterable
            placeholder="维修结果选择"
            :disabled="!canInput"
          >
            <el-option
              v-for="item of resultArr"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="是否审核 ：" class="w50p" prop="approve">
          <el-select
            v-model="formData.approve"
            clearable
            filterable
            placeholder="是否审核选择"
            :disabled="!canInput"
          >
            <el-option
              v-for="item of approveArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="nowChanceStau==='add'"
          label="处理过程："
          class="w50p"
          prop="processMode"
        >
          <el-input
            v-model="formData.processMode"
            clearable
            :rows="2"
            type="textarea"
            placeholder="请输入处理过程述"
            :disabled="!canInput"
          />
        </el-form-item>
        <el-form-item label="故障描述：" class="w50p" prop="description">
          <el-input
            v-model="formData.description"
            clearable
            :rows="2"
            type="textarea"
            placeholder="请输入故障描述"
            :disabled="!canInput"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button
          v-if="nowChanceStau==='add'||nowChanceStau==='edit'"
          type="primary"
          class="savebtn"
          @click="save('ruleForm')"
        >保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import MultipleUpimage from "@/components/uploadimage/MultipleUploadimage.vue";
import repairRecordApi from "@/api/equip-repair-manage/repair-record";
import sparePartsInputApi from "@/api/spare-part-manage/spare-parts-input";
import failureToReportApi from "@/api/equip-repair-manage/failure-to-report";
import equipTypeApi from "@/api/equip-manage/equip-type/index";
import equipScrapRecordApi from "@/api/equip-manage/equip-scrap-record";
import faultKeyManageApi from "@/api/equip-repair-support/fault-key-manage";
export default {
  name: "",
  components: {},
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: "add"
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      }
    },
    topitemtypeId: {
      type: String,
      default: ""
    },
    hitchTypeArr: {
      type: [Array],
      default: () => {
        return [];
      }
    },
    userList: {
      type: [Array],
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      formData: { repairConsumeBOList: [{ num: "", deviceCode: "" }] },
      rules: {
        hitchTypeCode: [
          {
            required: true,
            message: "请选择故障类型",
            trigger: ["change", "blur"]
          }
        ],
        equipmentCode: [
          { required: true, message: "请选择设备", trigger: ["change", "blur"] }
        ],
        discoverNodes: [
          {
            required: true,
            message: "请选择故障节点",
            trigger: ["change", "blur"]
          }
        ],
        proposer: [
          {
            required: true,
            message: "请选择上报人",
            trigger: ["change", "blur"]
          }
        ],
        applyDate: [
          {
            required: true,
            message: "请选择上报日期",
            trigger: ["change", "blur"]
          }
        ],
        expiryDate: [
          {
            required: true,
            message: "请选择截止日期",
            trigger: ["change", "blur"]
          }
        ],
        repairNature: [
          {
            required: true,
            message: "请选择维修方式",
            trigger: ["change", "blur"]
          }
        ],
        // deviceCode: [
        //   { required: true, message: "请选择备件消耗", trigger: ["change", "blur"] }
        // ],
        result: [
          {
            required: true,
            message: "请选择维修结果",
            trigger: ["change", "blur"]
          }
        ],
        repairDate: [
          {
            required: true,
            message: "请选择维修日期",
            trigger: ["change", "blur"]
          }
        ],
        approve: [
          {
            required: true,
            message: "请选择是否审核",
            trigger: ["change", "blur"]
          }
        ]
      },
      // 故障节点
      discoverNodesArr: ["点检发现", "保养发现"],
      showDialog: this.show,
      repairNatureArr: [
        { id: "NATURE_IN", name: "委内维修" },
        { id: "NATURE_OUT", name: "委外维修" }
      ],
      resultArr: ["维修完成", "维修失败"],
      approveArr: [
        { name: "是", id: true },
        { name: "否", id: false }
      ],
      sparePartArr: [],
      canInput: true,
      // uploadNum: 0,
      // uploadSize: 0,
      uploadFileList: [],
      equipmentArr: [],
      keysArr: [],
      allkeysArr: [],
      // 设备类型数组
      equipmentTypeList: [],
      defaultProps: {
        children: "childList",
        value: "equipmentTypeCode",
        label: "equipmentTypeName",
        emitPath: false,
        checkStrictly: true
      }
    };
  },

  watch: {
    show(v) {
      this.showDialog = v;
    },
    nowChanceStau(v) {
      this.canInput = true;
      this.uploadFileList = [];
      if (v === "add") {
        this.queryAllEnable();
        this.formData = {};
        this.$set(this.formData, "repairConsumeBOList", [
          { num: "", deviceCode: "" }
        ]);
        this.formData.repairNature = this.topitemtypeId;
      }
      if (v === "edit") {
        this.queryNotDiscardAndDisable();
        this.formData = this.editObject;
        if (this.formData.repairRecordVO) {
          this.formData.repairConsumeBOList = this.formData.repairRecordVO.repairConsumeVoList;
          this.formData.repairNature = this.formData.repairRecordVO.repairNature;
          this.formData.repairDate = this.formData.repairRecordVO.repairDate;
          this.formData.handUsername = this.formData.repairRecordVO.handUsername;
          this.formData.result = this.formData.repairRecordVO.result;
          this.formData.cost = this.formData.repairRecordVO.cost;
        }
        if (this.formData.repairWordVOList) {
          let list = [];
          this.formData.repairWordVOList.forEach(a => {
            var index = this.allkeysArr.findIndex(
              k => k.hitchKeywordId === a.hitchKeywordId
            );
            if (index !== -1) {
              list.push(this.allkeysArr[index].keywordCode);
            }
          });
          this.formData.repairWordBOList = list;
        } else {
          this.formData.repairWordBOList = [];
        }
        this.query(this.editObject.repairTaskCode);
      }
      if (v === "showdetail") {
        this.canInput = false;
        this.formData = this.editObject;
        if (this.formData.repairRecordVO) {
          this.formData.repairConsumeBOList = this.formData.repairRecordVO.repairConsumeVoList;
          this.formData.repairNature = this.formData.repairRecordVO.repairNature;
          this.formData.repairDate = this.formData.repairRecordVO.repairDate;
          this.formData.handUsername = this.formData.repairRecordVO.handUsername;
          this.formData.result = this.formData.repairRecordVO.result;
          this.formData.cost = this.formData.repairRecordVO.cost;
        }
        if (this.formData.repairWordVOList) {
          let list = [];
          this.formData.repairWordVOList.forEach(a => {
            var index1 = this.allkeysArr.findIndex(
              k => k.hitchKeywordId === a.hitchKeywordId
            );
            if (index1 !== -1) {
              list.push(this.allkeysArr[index1].keywordCode);
            }
          });
          this.formData.repairWordBOList = list;
        } else {
          this.formData.repairWordBOList = [];
        }
        this.query(this.editObject.repairTaskCode);
      }
    }
  },
  created() {
    this.queryPageKeyList();
    this.querySparePart();
    this.queryEquipmentType();
    this.queryAllEnable();
  },
  mounted() {},
  methods: {
    changeKey(e) {
      this.$set(this.formData, this.formData.repairWordBOList, e);
      // this.$forceUpdate()
      this.formData = { ...this.formData };
    },
    queryPageKeyList() {
      // 获取数据
      let param = {
        page: 1,
        size: 1000
      };
      faultKeyManageApi.queryPageList(param).then(res => {
        if (res.code === 1) {
          let data = res.data || {};
          this.allkeysArr = data.content || [];
          this.keysArr = data.content || [];
        }
      });
    },
    // 关联设备类型，根据父级查询子级
    queryEquipmentType() {
      // 获取数据
      equipTypeApi.queryTree({}).then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          this.equipmentTypeList = data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    changeEquipmentTypeCode() {
      if (this.formData.equipmentTypeCode) {
        if (this.nowChanceStau === "add") {
          this.queryAllEnable();
        }
        this.queryKey();
        if (this.nowChanceStau === "edit") {
          this.queryNotDiscardAndDisable();
        }
      } else {
        this.keysArr = this.allkeysArr;
      }
    },
    // 查询所有启用的设备
    queryAllEnable() {
      this.equipmentArr = [];
      let params = {
        equipmentTypeCode:
          this.formData && this.formData.equipmentTypeCode
            ? this.formData.equipmentTypeCode
            : ""
      };
      equipScrapRecordApi.queryAllEnable(params).then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          this.equipmentArr = data;
          // for (var i in data) {
          //   this.equipmentArr.push({
          //     equipmentName: data[i],
          //     equipmentCode: i
          //   })
          // }
        }
      });
    },
    // 查询所有不是报废以及禁用的设备
    queryNotDiscardAndDisable() {
      this.equipmentArr = [];
      let params = {
        equipmentTypeCode:
          this.formData && this.formData.equipmentTypeCode
            ? this.formData.equipmentTypeCode
            : void 0,
        equipmentName: void 0
      };
      equipScrapRecordApi.queryNotDiscardAndDisable(params).then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          this.equipmentArr = data;
        }
      });
    },
    // 条件查询关键字
    queryKey() {
      this.keysArr = [];
      // 获取数据
      faultKeyManageApi.query(this.formData.equipmentTypeCode).then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          this.keysArr = data;
        }
      });
    },
    query(data) {
      // // 获取数据
      // var form = new FormData()
      // form.append('hitchInfoCode', data)
      failureToReportApi.queryByHitchInfoId(data).then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          this.uploadFileList = data;
          this.uploadFileList.forEach(a => {
            a.name = a.pictureName;
          });
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // // 上传图片大小不能超过
    // beforeUpload(file) {
    //   const isLtSize = this.uploadSize / 1024 / 1024 < 100;
    //   if (!isLtSize) {
    //     this.$message.error("单次上传文件大小总和不能超过 100MB!");
    //     return false;
    //   }
    //   return true;
    // },
    // // 获取上传文件的数量
    // handleChangeFile() {
    //   var upload_img = document.getElementsByClassName("upload-file");
    //   if (upload_img && upload_img.length > 0) {
    //     var upload = upload_img[0].getElementsByTagName("input");
    //     if (
    //       upload &&
    //       upload.length > 0 &&
    //       upload[0].files &&
    //       upload[0].files.length > 0
    //     ) {
    //       this.uploadNum = upload[0].files.length;
    //       this.uploadSize = 0;
    //       upload[0].files.forEach(kit => {
    //         this.uploadSize = this.uploadSize + kit.size;
    //       });
    //     }
    //   }
    // },
    handleRemove(file) {
      if (file.hitchPictureCode) {
        let index = this.uploadFileList.findIndex(a => a.uid === file.uid);
        var form = new FormData();
        form.append("hitchPictureCode", file.hitchPictureCode);
        failureToReportApi.delByHitchPictureCode(form).then(res => {
          if (res.code === 1) {
            this.uploadFileList.splice(index, 1);
          }
        });
      } else {
        let index1 = this.uploadFileList.findIndex(
          a => a.uid === file.file.uid
        );
        if (index1 !== -1) {
          this.uploadFileList.splice(index1, 1);
        }
      }
    },
    // 上传文件
    handleFile(file) {
      this.loadFilesing = true;
      this.uploadFileList.push(file.file);
      this.loadFilesing = false;
    },
    // 点击添加按按钮
    addDeviceCodes() {
      let list = {
        deviceCode: "",
        num: ""
      };
      this.$set(
        this.formData.repairConsumeBOList,
        this.formData.repairConsumeBOList.length,
        list
      );
      this.formData = { ...this.formData };
    },
    // 删除改行
    delDeviceCodes(index) {
      this.formData.repairConsumeBOList.splice(index, 1);
    },
    // 备件
    querySparePart() {
      // 获取数据
      let param = {
        page: 1,
        size: 1000,
        entity: {
          input: 1
        }
      };
      sparePartsInputApi.queryPageList(param).then(res => {
        if (res.code === 1) {
          let data = res.data;
          this.sparePartArr = data.content;
        }
      });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          let repairConsumeBOList = [];
          this.formData.repairConsumeBOList.forEach(kit => {
            if (kit.deviceCode) {
              repairConsumeBOList.push(kit);
            }
          });
          this.formData.repairConsumeBOList = repairConsumeBOList;
          var repairWordBOList = [];
          this.formData.repairWordBOList.forEach(a => {
            repairWordBOList.push({ keywordCode: a });
          });
          this.formData.organizationMark = sessionStorage.organizationMark;
          this.formData.repairWordBOList = repairWordBOList;
          if (this.nowChanceStau === "edit") {
            this.formData.repairRecordId = this.formData.repairRecordVO.repairRecordId;
            this.formData.repairRecordCode = this.formData.repairRecordVO.repairRecordCode;
            repairRecordApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                if (this.uploadFileList.length > 0) {
                  this.upPicture(this.formData.repairTaskCode);
                }
              } else {
                this.$message.error(res.msg);
              }
            });
          } else if (this.nowChanceStau === "add") {
            repairRecordApi.add(this.formData).then(res => {
              if (res.code === 1) {
                let data = res.data || {};
                this.$message.success(res.msg);
                if (this.uploadFileList.length > 0) {
                  this.upPicture(data.repairTaskCode);
                }
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    upPicture(data) {
      var form = new FormData();
      this.uploadFileList.forEach(a => {
        if (!a.hitchPictureCode) {
          form.append("files", a);
        }
      });
      form.append("repairTaskCode", data);
      failureToReportApi.addPicture(form).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.close();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
.line-click {
  min-width: 30px;
  height: 30px;
  // background-color: aqua;
  display: flex;
  justify-content: center;
  align-items: center;
  border: snow 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 5px;
  color: #fff;
  background-color: #003947;
  cursor: pointer;
}
.hang-content {
  width: 100%;
  .hang-content-one {
    width: 100%;
    display: flex;
  }
}
.add-many {
  border: 1px solid #6ecae3;
  width: 40px;
  height: 40px;
  padding: 0;
  background-color: transparent;
  line-height: 40px;
  border-radius: 4px;
  color: rgb(161, 154, 154);
  font-weight: 600;
  i {
    font-size: 40px;
  }
}
</style>
